# encoding: UTF-8

"""
"""


from base.ctaBase import *
from ctaTemplate import CtaTemplate


########################################################################
class ChasingTickStrategy(CtaTemplate):
    """ChasingTick策略"""
    className = 'ChasingTick'
    author = u'何雨'

    # 策略变量
    bar = None
    barMinute = EMPTY_STRING

    initDays = 7
    hisBarOpen = []
    hisBarClose = []
    hisBarHigh = []
    hisBarLow = []

    self.hisTick = []

    pos = 0

    upLimitRatio = 0.7
    downLimitRatio = 0.7

    limitProfit = 20
    limitLost = 10

    orderSlippage = 0.5

    currTime = ""


    #----------------------------------------------------------------------
    def __init__(self, ctaEngine, setting):
        """Constructor"""
        super(ChasingTickStrategy, self).__init__(ctaEngine, setting)
        
    #----------------------------------------------------------------------
    def onInit(self):
        """初始化策略（必须由用户继承实现）"""
        self.writeCtaLog(u'ChasingTick策略初始化')
        
        initData = self.loadBar(self.initDays)
        for bar in initData:
            self.onBar(bar)
        
        self.putEvent()
        
    #----------------------------------------------------------------------
    def onStart(self):
        """启动策略（必须由用户继承实现）"""
        self.writeCtaLog(u'ChasingTick策略启动')
        self.putEvent()
    
    #----------------------------------------------------------------------
    def onStop(self):
        """停止策略（必须由用户继承实现）"""
        self.writeCtaLog(u'ChasingTick策略停止')
        self.putEvent()
        
    #----------------------------------------------------------------------
    def onTick(self, tick):
        """收到行情TICK推送（必须由用户继承实现）"""

        #print "收到最新行情 vtSymbol = %s, date = %s, time = %s ,lastPrice = %s " % (tick.vtSymbol, tick.date, tick.time, tick.lastPrice)
        self.writeCtaLog(u"收到最新行情 vtSymbol = %s, date = %s, time = %s ,lastPrice = %s " % (tick.vtSymbol, tick.date, tick.time, tick.lastPrice))
        self.hisTick.append(tick)
        if len(self.hisTick) <3:
            return
        
        buy = self.hisTick[-3].bidPrice1 > self.hisTick[-2].bidPrice1 and 
            

    #----------------------------------------------------------------------
    def onBar(self, bar):
        """收到Bar推送（必须由用户继承实现）"""

        #记录历史数据
        self.hisBarClose.append(bar.close)
        self.hisBarHigh.append(bar.high)
        self.hisBarOpen.append(bar.open)
        self.hisBarLow.append(bar.low)

        print self.inited
        if self.inited:
           self.check(bar)
    #----------------------------------------------------------------------
    def check(self, bar):
        """检查交易信号"""
        self.currTime = bar.datetime.strftime("%H%M%S")
        if (len(self.hisBarLow) < self.NPeriod):
            return

        print("New bar : date = %s, time = %s, open = %f, close = %f, high = %f, low = %f" % (bar.date, bar.time, bar.open, bar.close, bar.high, bar.low))
        self.writeCtaLog(u"New bar : date = %s, time = %s, open = %f, close = %f, high = %f, low = %f" % (bar.date, bar.time, bar.open, bar.close, bar.high, bar.low))
        #收盘前平仓
        if (self.currTime >="145500") and (self.currTime <= "145800") \
            and (not self.isPositionNextDate) and (self.getTotalPosition() != 0)\
                and self.isFinishedOrders():
            if self.getLongPosition() != 0:
                self.sell(bar.open, 1)
            elif self.getShortPosition() != 0:
                self.cover(bar.open, 1)
            return

        #止盈
        if self.isLimitProfit:
            if self.isFinishedOrders() and self.getTotalPosition() >0:
                #止损平多
                if self.getLongPosition() >0:
                    if (bar.open + self.limitProfit) > self.getLongCostPrice():
                        self.sell(bar.close, 1)
                        return
                #止损平空
                if self.getShortPosition() >0:
                    if (bar.open + self.limitProfit) < self.getShortCostPrice():
                        self.cover(bar.close, 1)
                        return

        #止损
        if self.isLimitLose :
            if self.isFinishedOrders() and self.getTotalPosition() >0:
                #止损平多
                if self.getLongPosition() >0:
                    if (bar.open + self.limitLost) < self.getLongCostPrice():
                        self.sell(bar.close, 1)
                        return
                #止损平空
                if self.getShortPosition() >0:
                    if (bar.open + self.limitLost) > self.getShortCostPrice():
                        self.cover(bar.close, 1)
                        return


        #

        HH = max(self.hisBarHigh[-self.NPeriod:])
        HC = max(self.hisBarClose[-self.NPeriod:])
        LC = min(self.hisBarClose[-self.NPeriod:])
        LL = min(self.hisBarLow[-self.NPeriod:])

        rangeBar = max(HH - LC, HC - LL)


        upLimitPrice = bar.open + self.upLimitRatio * rangeBar
        downLimitPrice = bar.open - self.downLimitRatio * rangeBar

        lastPrice = bar.close

        print rangeBar, upLimitPrice, downLimitPrice, lastPrice
        self.writeCtaLog(u"当前bar数据 : rangeBar = %f, upLimitPrice = %f, downLimitPrice = %f, lastPrice = %f" % (rangeBar, upLimitPrice, downLimitPrice, lastPrice))

        if bar.high > upLimitPrice:
            if self.isFinishedOrders() and self.getLongPosition() == 0 and self.getTotalPosition() == 0:
                self.buy(bar.high + self.orderSlippage, 1)
                print("买入开仓1手")
                self.writeCtaLog(u"买入开仓1手")
            elif self.isFinishedOrders() and self.getLongPosition() == 0 and self.getTotalPosition() != 0:
                self.cover(bar.close - self.orderSlippage, 1)
                self.buy(bar.close + self.orderSlippage, 1)
                print("买入平仓再开仓1手")
                self.writeCtaLog(u"买入平仓再开仓1手")

        if bar.low < downLimitPrice:
            if self.isFinishedOrders() and self.getShortPosition() == 0 and self.getTotalPosition() == 0:
                self.short(bar.low - self.orderSlippage, 1)
                print("卖出开仓1手")
                self.writeCtaLog(u"卖出开仓1手")

            elif self.isFinishedOrders() and self.getShortPosition() == 0 and self.getTotalPosition() != 0:
                self.sell(bar.low + self.orderSlippage, 1)
                self.short(bar.low - self.orderSlippage, 1)
                print("卖出平仓, 再开仓1手")
                self.writeCtaLog(u"卖出平仓, 再开仓1手")
                
        # 发出状态更新事件
        self.putEvent()
        
    #----------------------------------------------------------------------
    def onOrder(self, order):
        """收到委托变化推送（必须由用户继承实现）"""
        # 对于无需做细粒度委托控制的策略，可以忽略onOrder
        pass
    
    #----------------------------------------------------------------------
    def onTrade(self, trade):
        """收到成交推送（必须由用户继承实现）"""
        # 对于无需做细粒度委托控制的策略，可以忽略onOrder
        pass
    

